<template>
  <main>
    <am-container>
      <p> -- 当前操作: {{ crOup }}</p>
      <hr data-am-widget="divider" style="" class="am-divider am-divider-default" />
      <form class="am-form am-form-horizontal" ref="form">
        <fieldset>

          <!-- 作品名称name -->
          <div :class="['am-form-group', 'am-form-group-sm', 'am-form-feedback', { 'am-form-icon am-form-error': !validator.name.vld }]">
            <label for="name" class="am-u-sm-12 am-u-md-2 am-form-label">作品名称</label>
            <div class="am-u-sm-12 am-u-md-10">
              <am-input id="name" placeholder="作品名称" autocomplete="off" v-model="works.name" />
              <template v-if="!validator.name.vld">
                <span class="am-icon-times"></span>
                <small class="am-text-danger">{{ validator.name.msg }}</small>
              </template>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 作品主图mainPic -->
          <div :class="['am-form-group', 'am-form-group-sm', {'am-form-error': !validator.mainPic.vld }]">
            <label class="am-u-sm-12 am-u-md-2 am-form-label" for="mainPic">作品主图</label>
            <div class="am-u-sm-12 am-u-md-10">
              <upload-img ref="mainPic"
                :imgCount.sync="validator.mainPic.count"
                :imgVali.sync="validator.mainPic.vld"
                :imgPath.sync="works.mainPic"
                :listType="'text'"
                :showFileList="false"
                :isSizeVali="true" />
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 作品图集worksPic -->
          <div :class="['am-form-group', 'am-form-group-sm', {'am-form-error': !validator.worksPic.vld }]">
            <label class="am-u-sm-12 am-u-md-2 am-form-label" for="worksPic">作品图集</label>
            <div class="am-u-sm-12 am-u-md-10">
              <am-scrollbar :height="300" :auto-hide="false" ref="scrollbar">
                <upload-img ref="pics"
                  :imgCount.sync="validator.worksPic.count"
                  :imgVali.sync="validator.worksPic.vld"
                  :imgPath.sync="works.worksPic"
                  :multiple="true"
                  :showFileList="true"
                  :listType="'picture'" />
              </am-scrollbar>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 全景图url、qart -->
          <div :class="['am-form-group', 'am-form-group-sm', 'am-form-feedback', { 'am-form-icon am-form-error': !validator.panoramaUrl.vld }]">
            <label for="panoramaUrl" class="am-u-sm-12 am-u-md-2 am-form-label">全景图地址</label>
            <div class="am-u-sm-12 am-u-md-10">
              <am-input id="panoramaUrl" v-model="works.panoramaUrl" placeholder="全景图地址（自动生成二维码）" autocomplete="off" />
              <template v-if="!validator.panoramaUrl.vld">
                <span class="am-icon-times"></span>
                <small class="am-text-danger">{{ validator.panoramaUrl.msg }}</small>
              </template>
              <br />
              <!-- <vue-q-art :config="qartConfig"></vue-q-art> -->
              <!-- <qr-code :text="works.panoramaUrl"></qr-code> -->
            </div>
            <div class="am-u-sm-12">
              <qr-code :text="works.panoramaUrl"></qr-code>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 分类标签tags -->
          <div :class="['am-form-group', 'am-form-group-sm', {'am-form-error': !validator.worksTag.vld }]">
            <label for="tags" class="am-u-sm-12 am-u-md-2 am-form-label">分类标签</label>
            <div class="am-u-sm-12 am-u-md-3">
              <am-button type="button" @click="showModal">选择分类标签</am-button>
            </div>
            <div class="am-u-sm-12 am-u-md-7">
              <p class="am-text-danger" v-if="!validator.worksTag.vld">{{ validator.worksTag.msg }}</p>
              <p>
                <template v-for="tag in works.worksTag">
                  {{ tag.name }} \
                </template>
              </p>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 业主信息 -->
          <div class="am-form-group">
            <label for="owner" class="am-u-sm-12 am-u-md-2 am-form-label">业主信息</label>
            <div class="am-u-sm-12 am-u-md-5">
              <am-input placeholder="姓名，楼盘，联系方式" :disabled="true"></am-input>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 作品思路 -->
          <div class="am-form-group">
            <label for="introduction" class="am-u-sm-12 am-u-md-2 am-form-label">作品介绍</label>
            <div class="am-u-sm-12 am-u-md-10">
              <am-input id="introduction" type="textarea" rows="5" v-model="works.introduction" placeholder="作品思路介绍" />
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 作品上传提交 -->
          <div class="am-form-group">
            <div class="am-u-sm-10 am-u-sm-offset-2">
              <am-button type='button' v-if="!submitAbled" disabled>确认添加（请完善信息）</am-button>
              <am-button type="button" v-else @click="beforeSubmit">确认添加</am-button>
            </div>
          </div>
        </fieldset>
      </form>
    </am-container>

    <!-- 模态框 -->
    <modal :modalVisible.sync="modalVisible" :width="450">
      <div slot="选择作品分类标签"></div>
      <tags slot="body" ref="tags" :worksTags.sync="works.worksTag" />
      <am-button slot="footer" @click="closeModal" color="primary">确认添加</am-button>
    </modal>
  </main>
</template>

<script>
import UploadImg from '@/components/UploadImg'
import Modal from '@/components/Modal'
import Tags from '@/views/personal/panel/Tags'
import VueQArt from 'vue-qart'
import QrCode from '@/components/QrCode'

export default {
  name: 'create',
  data() {
    return {
      minWorksPic: 1,
      isPicReady: {// 图片组件是否回传完成
        mainPic: false,
        pic: false
      },
      modalVisible: false,// 模态框显示
      qartConfig: {// 二维码信息
        value: 'www.baidu.com',// this.works.panoramaUrl
        imagePath: '/static/white.png',// this.works.panoramaPath
        filter: 'color'// threshold 黑白
      },
      works: this.structure.UPLOADWORKS(),// 一个作品
      validator: {// 字段验证
        name: {
          vld: true,
          msg: '名称不能为空'
        },
        mainPic: {
          count: 0,
          vld: true,
          msg: '必须上传一张主图'
        },
        worksPic: {
          count: 0,
          vld: true,
          msg: '存在不符合尺寸的图片或选择至少2张图，请重新选择'
        },
        worksTag: {
          vld: true,
          msg: '必须选择标签'
        },
        mainPic: {
          vld: true,
          msg: '图片尺寸不符合，请重新选择'
        },
        panoramaUrl: {
          vld: true,
          msg: '不是合法url地址'
        }
      },


      /**
       * 非响应式使用
       */
      validate: {// 验证器
        'works.name': (val = this.works.name) => this.validator.name.vld = !!val,
        'works.mainPic': (val = this.mainPicCount) => val > 0,
        'works.worksPic': (val = this.worksPicCount) => val > this.minWorksPic,
        'works.worksTag': (val = this.works.worksTag) => this.validator.worksTag.vld = (val.length > 0),
        // 符合url规则
        'works.panoramaUrl': (val = this.works.panoramaUrl)=> this.validator.panoramaUrl.vld = /[a-zA-z]+:\/\/[^\s]*/g.test(val)
      },
      loadingIns: {},
    }
  },
  components: {
    UploadImg, VueQArt, Modal, Tags, QrCode
  },
  computed: {
    crOup() {
      if(this.$route.params.id === 'c') {
        return '新增';
      } else {
        return '修改';
      }
    },
    // 主图数量
    mainPicCount() {
      return this.validator.mainPic.count;
    },
    // 图集数量
    worksPicCount() {
      return this.validator.worksPic.count;
    },

    /**是否可以提交 */
    submitAbled() {
      if(
        this.validator.mainPic.count === 0 ||
        this.validator.worksPic.count === 0 ||
        this.works.name === '' ||
        this.works.worksTag.length === 0
      ) {
        return false;
      } else {
        return this.goValidation();
      }
    }
  },
  methods: {
    ready() {
      this.$store.commit('clearTags');
      this.setDesignerID();
    },

    /**设计师id号 */
    setDesignerID() {
      this.works.designerID = this.designerID;
    },

    /**显示标签模态框 */
    showModal() {
      this.modalVisible = true;
    },

    /**提交前的表单验证 */
    goValidation() {
      let isPass = true;// 表单是否通过所有验证
      Object.values(this.validate).forEach(fun => {
        // 提交前把所有validate走一遍
        isPass = fun() && isPass;
      });
      return isPass;
    },

    /**先执行上传，用以触发submit */
    beforeSubmit() {
      this.loadingIns = this.$loading({ loadingText: '正在处理，上传作品成功后请等待审核通过' });
      this.$refs.mainPic.submit();
      this.$refs.pics.submit();

      // if(!this.goValidation()) {
      //   this.loadingIns.close();
      // } else {
      //   this.$refs.mainPic.submit();
      //   this.$refs.pics.submit();
      // }


      // /**
      //  * 二次上传
      //  */
      // if(this.isPicReady.mainPic === true && this.isPicReady.pic === true) {
      //   if(this.goValidation()) {
      //     this.works.worksTag = this.works.worksTag.map(tag => tag.id);
      //     this.works.panorama = this.qartConfig.value;
      //     this.submit();
      //   } else {
      //     this.loadingIns.close();
      //     this.$notify({
      //       message: '请按提示完善信息',
      //       type: 'warning'
      //     });
      //   }
      // }
    },

    submit() {// h5原生验证、提交
      const delay = 999;
      Promise.resolve()
      .then(() => {
        this.works.worksPic = this.works.worksPic.toString();
        this.works.worksTag = this.works.worksTag.toString();
        return this.dgpost(this.api.UPLOADWORKS, this.works);
      }).then(res => {
        console.log('创建作品成功');
        setTimeout(() => {
          this.loadingIns.close();
        }, delay);

        this.$parent.curTab = 0;
        setTimeout(() => {
          this.$router.push('/personal/panel/table');
        }, (delay * 1.2));
      }).catch(err => {
        this.loadingIns.close();
        this.$message({
          title: '创建出错',
          type: 'error',
          message: err.msg || this.MSG.UNKNOWN
        });

      });
    },

    /**
     * 
     */
    btnAct(name) {
      this.funs[name]();
    },
    closeModal() {
      this.modalVisible = false;
    },
  },
  watch: {
    /**
     * 上传完成
     * 替异步做法，触发提交
     */
    'works.mainPic': function(val) {
      this.isPicReady.mainPic = !!val;
      // this.validate['works.mainPic'](val)
    },
    'works.worksPic': function(val) {
      this.isPicReady.pic = (val.length > this.minWorksPic);
      this.validate['works.worksPic'](val);// 主要是数量错误提示
    },
    isPicReady: {
      handler(val) {
        if(val.mainPic === true && val.pic === true) {
          if(this.goValidation()) {
            this.works.worksTag = this.works.worksTag.map(tag => tag.id);
            this.works.panorama = this.qartConfig.value;
            this.submit();
          } else {
            this.loadingIns.close();
            this.$notify({
              message: '请按提示完善信息1',
              type: 'warning'
            });
          }
        }
      },
      deep: true
    },


    /**
     * 输入同时验证
     */
    'works.name': function(val) {
      this.validate['works.name']();
    },
    'works.worksTag': function(val) {
      this.validate['works.worksTag']();
    },
    'works.panoramaUrl': function(val) {
      this.validate['works.panoramaUrl']();
    }
  },
  props: {
    designerID: String
  },
  mounted() {
    this.ready();
  }
}
</script>